<!--一般重点项目排序-->
<template>
  <rk-container :isFooter="false">
    <template #header_left>
      <RkButtonGroup :options="json_proj_sort"
        v-model="queryParams.queryType" />
    </template>
    <template #header_right />
    <template #aside>
      <rk-ad-ag-tree layoutTree=ad
        :agConfig="{code:'2300'}"
        @adNodeClick="handleAdNodeClick">
      </rk-ad-ag-tree>
    </template>
    <template #main>
      <rk-condition>
        <template #condition>
          <rk-condition-bar v-show="showCondition">
            <template #content>
              <el-form ref="form"
                :inline="true">
                <el-form-item label="申报批次">
                  <el-input v-model="queryParams.sbBatch"></el-input>
                </el-form-item>
                <el-form-item label="申报年度">
                  <el-date-picker v-model="queryParams.sbYear"
                    type="year" />
                </el-form-item>
              </el-form>
            </template>
            <template #buttons>
              <el-button type="primary">查询</el-button>
              <el-button type="primary"
                v-if="queryParams.queryType===0"
                @click="handleOperation('autoSort','自动排序','')">自动排序
              </el-button>
              <el-button type="danger"
                v-if="queryParams.queryType===1"
                @click="handleOperation('revokeSort','撤销排序','')">撤销排序
              </el-button>
              <el-button type="primary"
                v-if="queryParams.queryType===1"
                @click="handleOperation('confirm','确认','')">撤销确认
              </el-button>
              <el-button type="danger"
                v-if="queryParams.queryType===2"
                @click="handleOperation('revokeConfirm','撤销确认','')">撤销确认
              </el-button>
              <el-button v-if="queryParams.queryType===0"
                @click="handleOperation('save','保存','')">保存</el-button>
              <el-button v-if="queryParams.queryType===0"
                @click="handleOperation('export','导出','')">导出</el-button>
            </template>
          </rk-condition-bar>
        </template>
        <template #content>
          <rk-grid ref="reserveProjRef"
            title="一般债券备选项目申报"
            dataUrl="/alternateProject/sortPage"
            boxConfig
            :seqConfig="false"
            :params="queryParams"
            :columns="tableColumns"
            :loaded="handleLoaded">
            <template #sort_input_edit="{row,column}">
              <el-input v-model="row[column.field]"
                :disabled="queryParams.queryType!==1"></el-input>
            </template>
          </rk-grid>
        </template>
      </rk-condition>
    </template>
  </rk-container>
  <PrioriityProSortDialogView :dialog-type="dialogType"
    v-model:visible="showDialog"
    :ok="clickOk" />
</template>

<script setup>
import { getCurrentInstance, reactive, ref, unref, watch } from "vue";
import { json_proj_sort } from '@/common/button-data';
import PrioriityProSortDialogView from "../dialogs/PrioriityProSortDialogView.vue";
import { getMaxSortId } from "@/api/api-sort";
import { RkConfirmBox } from "@/components/message-box";
import { cancelProjSort, confirmProjSort, revokeConfirmProjSort, saveProjSort } from "../../../../api/api-sort";

const props = defineProps({
  //分类1：一般项目，2：专项项目
  catalog: {
    type: Number,
    default: 1
  }

})

const showCondition = ref(true)
const reserveProjRef = ref(null)
const { appContext } = getCurrentInstance();
const globalProxy = appContext.config.globalProperties;
const showDialog = ref(false)
// 查询参数
let queryParams = reactive({
  queryType:0,
  adCode: void 0,
  agCode: void 0,
  agId: void 0,
  bondTypeCode: props.catalog,
})

const dialogType = ref(0)

const sortData = ref([])
const tableColumns = ref([
  { field: 'sortId', title: '排序号', width: 100, align: 'left', slots: { edit: 'sort_input_edit' } },
  { field: 'agencyName', title: '申报单位', width: 250, align: 'left', },
  {
    field: 'proName', title: '项目名称', width: 250, align: 'left',
    renderer({ cellValue, row, column }) {
      return '<a  rel="opener" href="/page/debt/project-manage/common/pro-yhs.html?pro_id=' + row.PRO_ID + '" target="_blank">' + cellValue + '</a>';
    }
  },
  { field: 'proCode', title: '项目编码', width: 200, align: 'left', },
  { field: 'fiscalYear', title: '年度', width: 120, align: 'center', },
  { field: 'debtDeadlineName', title: '债券期限', width: 150, align: 'center', },
  {
    field: 'applyAmt',
    title: '申请金额（万元）',
    formatter: 'formatThousand',
    width: 200,
    sumable: true,
    align: 'right'
  },
  {
    field: 'expFuncName', title: '支出功能分类', width: 200, align: 'left'
  },
  {
    field: 'govBgtEcoName', title: '政府预算支出经济分类', width: 200, align: 'left'
  },
  {
    field: 'depBgtEcoName', title: '部门预算支出经济分类', width: 200, align: 'left'
  },
  {
    field: 'proCapital',
    title: '项目资本金（万元）',
    formatter: 'formatThousand',
    width: 200,
    sumable: true,
    align: 'right'
  },
  {
    field: 'bondTypeCode', title: '申请类型', width: 150, align: 'left'
  },
  { field: 'applyDate', title: '申报日期', width: 200, align: 'center' },
  { field: 'setupYear', title: '立项年度', width: 180, align: 'center' },
  { field: 'proTypeName', title: '项目类型', width: 150, align: 'left' },
  { field: 'fundInvestAreaCode', title: '资金投向领域', width: 250, align: 'left' },
  {
    field: 'totalBudget',
    title: '项目总概算',
    formatter: 'formatThousand',
    width: 200,
    sumable: true,
    align: 'right'
  },
  { field: 'proStatusName', title: '建设状态', width: 150, align: 'left' },
  { field: 'startDate', title: '开工日期', width: 150, align: 'center' },
  { field: 'endDate', title: '竣工日期', width: 150, align: 'center' },
  { field: 'remark', title: '备注', width: 120, align: 'left' },
])
const clickOk = async () => {
  if (dialogType.value === 1) {
    let select = selectData()
    if (select.data) {
      RkConfirmBox({
        title: '提示',
        content: `请确认是否${textName}？`,
        onSubmit: async () => {
          let applyIds = []
          let sortIds = []
          select.data.forEach(item => {
            applyIds.push(item.applyId)
            sortIds.push(item.sortId)
          })
          let params = Object.assign({}, { applyIds: applyIds.join(","), sortIds: sortIds.join(",") })
          const res = await confirmProjSort(params)
          if (res.code === 200) {
            globalProxy.$message({ message: `确认成功!`, type: 'success' })
            handleSearch()
          } else {
            if (res.msg) {
              globalProxy.$message({ message: res.msg, type: 'error' })
            } else {
              globalProxy.$message({ message: `确认失败!`, type: 'error' })
            }
          }
        },
        onCancel: () => {

        }
      })
    }
  } else if (dialogType.value === 0) {
    const resp = await getMaxSortId(queryParams.adCode)
    const { data, msg, code } = resp
    if (code === 200) {
      handleAutoSort(data)
    } else {
      globalProxy.$message({ message: `${msg}`, type: "error" });
    }
  }
  showDialog.value = false
}

//点击自动排序
const handleAutoSort = (num) => {
  let data = sortData.value
  data.forEach((item, index) => {
    item.sortId = num + (index + 1)
  })
  //重新载入数据
  reserveProjRef.value.reloadData(data)
}

//加载完成事件处理
const handleLoaded = (data) => {
  sortData.value = data
}

const handleOperation = (buttonType, textName, buttonStatus) => {
  //自动排序
  if (buttonType === 'autoSort') {
    if (!queryParams.adCode) {
      globalProxy.$message({ message: '请选择一个区划', type: "error" });
      return
    }
    if (!sortData.value || sortData.value.length === 0) {
      globalProxy.$message({ message: '没有可排序项目', type: "error" });
      return;
    }
    dialogType.value = 0
    showDialog.value = true
  }//撤销排序
  else if (buttonType === 'revokeSort') {
    let select = selectData()
    if (select.empty) {
      globalProxy.$message({ message: `请至少选择一条数据进行${textName}！`, type: "warning" });
      return;
    }
    if (select.data) {
      RkConfirmBox({
        title: '提示',
        content: `请确认是否${textName}？`,
        onSubmit: async () => {
          let applyIds = []
          select.data.forEach(item => {
            applyIds.push(item.applyId)
          })
          const res = await cancelProjSort({ applyIds })
          if (res.code === 200) {
            globalProxy.$message({ message: `${textName}成功!`, type: 'success' })
            handleSearch()
          } else {
            if (res.msg) {
              globalProxy.$message({ message: res.msg, type: 'error' })
            } else {
              globalProxy.$message({ message: `${textName}失败!`, type: 'error' })
            }
          }
        },
        onCancel: () => {

        }
      })
    }

  }//撤销确认
  else if (buttonType === 'revokeConfirm') {
    let select = selectData()
    if (select.empty) {
      globalProxy.$message({ message: `请至少选择一条数据进行${textName}！`, type: "warning" });
      return;
    }
    if (select.data) {
      RkConfirmBox({
        title: '提示',
        content: `请确认是否${textName}？`,
        onSubmit: async () => {
          let applyIds = []
          select.data.forEach(item => {
            applyIds.push(item.applyId)
          })
          let params = Object.assign({}, { applyIds: applyIds.join(",") })
          const res = await revokeConfirmProjSort(params)
          if (res.code === 200) {
            globalProxy.$message({ message: `${textName}成功!`, type: 'success' })
            handleSearch()
          } else {
            if (res.msg) {
              globalProxy.$message({ message: res.msg, type: 'error' })
            } else {
              globalProxy.$message({ message: `${textName}失败!`, type: 'error' })
            }
          }
        },
        onCancel: () => {

        }
      })
    }
  }//确认
  else if (buttonType === 'confirm') {
    let select = selectData()
    if (select.empty) {
      globalProxy.$message({ message: `请至少选择一条数据进行${textName}！`, type: "warning" });
      return;
    }
    dialogType.value = 1
    showDialog.value = true
  }
  //保存
  else if (buttonType === 'save') {
    let select = selectData()
    if (select.empty) {
      globalProxy.$message({ message: `请至少选择一条数据进行${textName}！`, type: "warning" });
      return;
    }
    if (select.data) {
      let count = select.data.filter(item => !item.sortId).count()
      if (count > 0) {
        RkConfirmBox({
          title: '提示',
          content: '排序号错误请重新排序否者无法保存!',
        })
        return;
      }
      RkConfirmBox({
        title: '提示',
        content: `请确认是否${textName}？`,
        onSubmit: async () => {
          let applyIds = []
          let sortIds = []
          select.data.forEach(item => {
            applyIds.push(item.applyId)
            sortIds.push(item.sortId)
          })
          let params = Object.assign({}, { applyIds: applyIds.join(","), sortIds: sortIds.join(",") })
          const res = await saveProjSort(params)
          if (res.code === 200) {
            globalProxy.$message({ message: `${textName}成功!`, type: 'success' })
            handleSearch()
          } else {
            if (res.msg) {
              globalProxy.$message({ message: res.msg, type: 'error' })
            } else {
              globalProxy.$message({ message: `${textName}失败!`, type: 'error' })
            }
          }
        },
        onCancel: () => {

        }
      })
    }

  } //导出
  else if (buttonType === 'export') {

  }
}
const selectData = () => {
  const rows = reserveProjRef.value.getCheckboxRecords()
  if (!rows || rows.length === 0) {
    return { empty: true, data: void 0 }
  }
  return { empty: false, data: rows }
}
/**查询 */
const handleSearch = () => {
  reserveProjRef.value.searchEvent()
}

/**重置 */
const handleReset = () => {
  reserveProjRef.value.resetEvent()
}

// agCode监听
const handleAdNodeClick = (obj) => {
  if (obj && obj.data) {
    if (obj.data.code) {
      queryParams.adCode = obj.data.code
      handleSearch()
    }
  }
}
</script>

<style scoped>
</style>
